/**
 * 常用工具方法
 */
import Cookies from 'js-cookie';

export default {
  ENV: process.env.NODE_ENV,
  MSG: process.env.VUE_APP_MSG,
  // API_PREFIX: process.env.VUE_APP_BASE_API,
  API_PREFIX: 'http://127.0.0.1:8090',
  token: 'Authorization',
  logout: false,

  lsPut(key, val) {
    window.localStorage.setItem(key, JSON.stringify(val));
  },
  lsGet(key, defaultVal) {
    return JSON.parse(window.localStorage.getItem(key) || defaultVal);
  },
  setToken(res) {
    this.logout = false;
    const now = Date.now();
    if (res && res.data && res.data.token && res.data.expiration) {
      window.localStorage.setItem(this.token, JSON.stringify({
        token: res.data.token,
        tokenExpiration: now + res.data.expiration,
      }));
    }
  },
  getToken() {
    let tokenObj = window.localStorage.getItem(this.token);
    tokenObj = tokenObj ? JSON.parse(tokenObj) : {};
    return tokenObj;
  },
  clearToken() {
    this.logout = true;
    window.localStorage.removeItem(this.token);
  },
  cookieSet(key, val, expires) {
    if (expires) {
      Cookies.set(key, val, { expires });
    } else {
      Cookies.set(key, val);
    }
  },
  cookieGet(key) {
    return Cookies.get(key);
  },
  /**
   * 检查对象的真实类型
   */
  checkType(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
  },
  /**
   * 深拷贝对象
   * @param obj 被拷贝的对象
   * @param containsPrototype 是否拷贝父级或原型的属性
   */
  clone(obj, containsPrototype = true) {
    let result;
    const
      objType = this.checkType(obj);
    if (objType === 'Object') {
      result = {};
    } else if (objType === 'Array') {
      result = [];
    } else {
      return obj;
    }
    // eslint-disable-next-line no-restricted-syntax
    for (const property in obj) {
      // eslint-disable-next-line no-prototype-builtins
      if (containsPrototype || obj.hasOwnProperty(property)) {
        const val = obj[property];
        if (this.checkType(val) === 'Object' || this.checkType(val) === 'Array') {
          result[property] = this.clone(val);
        }
        result[property] = val;
      }
    }
    return result;
  },
  /**
   *  合并用户配置并返回新对象
   * @param conf  用户配置
   * @param defaultConf 默认配置
   */
  merge(conf, defaultConf) {
    const result = this.clone(conf);
    // eslint-disable-next-line no-restricted-syntax
    for (const property in defaultConf) {
      if (this.checkType(result[property]) === 'Undefined') {
        result[property] = this.clone(defaultConf[property]);
      } else if (this.checkType(result[property]) === 'Object') {
        result[property] = this.merge(result[property], defaultConf[property]);
      }
    }
    return result;
  },
};
